<script setup>
    import { ref, watch, onMounted, onBeforeUnmount, nextTick, toRaw } from "vue"
    import { ArrowLeftOutlined, ArrowRightOutlined, Loading3QuartersOutlined } from '@ant-design/icons-vue'
    import { useElementBounding, useElementVisibility, useRefHistory, useClipboard, useDebounceFn } from '@vueuse/core'
    import { message } from 'ant-design-vue'
    import request from '@/common/utils/request'
    import utils from "@/common/utils/utils"
    import store from "@/store/index";
    const props = defineProps({
        appKey: {
            type: String,
            required: true
        },
        url: {
            type: String,
            required: true
        },
        auth_url: {
            type: String,
            default: ''
        },
        option: {
            type: Object,
            default: () => ({})
        }
    })

    const emit = defineEmits(['logined', 'browerInit'])

    const windowViewUrl = ref(props.url)
    const windowViewRef = ref()
    const browerViewer = ref()

    const { undo, redo, canUndo, canRedo } = useRefHistory(windowViewUrl)
    const { x, y, width, height } = useElementBounding(windowViewRef)
    const targetIsVisible = useElementVisibility(windowViewRef)
    const { copy } = useClipboard({ source: windowViewUrl })

    const syncUserAuthInfo = useDebounceFn(async ({ headers }) => {
        try{
            await request.post("/work_ai", "/org/platform/account/user/sync", {
                org_id: utils.getOrgId(),
                header: headers,
                source: props.appKey,
                team_id: store.state.user.teamId,
            })
        }catch(e){
            console.log(e,'error');
                if(e.code==37100){
                 return message.error(err.msg)
                }
        }

        emit('logined', {
            ...headers,
            appKey: props.appKey
        })
    }, 1000)
        
    const copyWindowUrl = () => {
        copy()
        message.success('复制成功')
    }

    onBeforeUnmount(() => {
        destoryAppWindow()
    })

    const destoryAppWindow = () => {
        browerViewer.value?.destory()
    }

    const retreatAppPage = async () => {
        if(canUndo.value){
            undo()
            await nextTick()
            browerViewer.value?.navigateTo(windowViewUrl.value)
        }
    }

    const forwardAppPage = async () => {
        if(canRedo.value){
            redo()
            await nextTick()

            browerViewer.value?.navigateTo(windowViewUrl.value)
        }
    }

    const reloadAppPage = () => {
        browerViewer.value?.reload()
    }

    const clearAppCache = () => {
        browerViewer.value?.clearCache()
    }

    const resizeAppWindow = () => {
        browerViewer.value?.resize({
            width: parseInt(width.value),
            height: parseInt(height.value),
            y: parseInt(y.value),
            x: parseInt(x.value),
        })
    }

    watch(targetIsVisible, (visible) => {
        if(visible){
            resizeAppWindow()
            browerViewer.value?.show()
        }
    })

    watch([width, height, x, y], () => {
        if(targetIsVisible.value){
            resizeAppWindow()
        }
    })

    onMounted(async () => {
        browerViewer.value = await window.client.createBrowerView(
            windowViewUrl.value,
            {
                width: parseInt(width.value),
                height: parseInt(height.value),
                y: parseInt(y.value),
                x: parseInt(x.value)
            },
            toRaw(props.option)
        )

        browerViewer.value?.show()

        browerViewer.value.navigateDidEvent((url) => {
            windowViewUrl.value = url
        })

        if(props.auth_url){
          browerViewer.value.beforeRequest(props.auth_url, async (res) => {
            if(props.appKey === 'douyin') {
              await utils.delay(6000)

              const localData = [
                'security-sdk/s_sdk_cert_key',
                'security-sdk/s_sdk_crypt_sdk',
                'security-sdk/s_sdk_pri_key',
                'security-sdk/s_sdk_pub_key',
                'security-sdk/s_sdk_server_cert_key',
                'security-sdk/s_sdk_sign_data_key/token',
                'security-sdk/s_sdk_sign_data_key/web_protect',
              ]

              const localDataPromises = localData.map((item) => {
                return executeJavaScript(`localStorage.getItem("${item}");`).then(res => {
                  return {
                    key: item,
                    value: res,
                  }
                })
              })

              const localDataResult = await Promise.all(localDataPromises)

              res = {
                ...res,
                headers: {
                  ...res.headers,
                  localdata: localDataResult
                },
              }
            }

            syncUserAuthInfo(res)
          })
        }

        emit('browerInit', browerViewer.value)

        window.addEventListener('beforeunload', () => {
            destoryAppWindow()
        })
    })
</script>

<template>
    <div class="flex flex-col w-full h-full">
        <div class="flex header align-center">
            <div class="flex gap-10 align-center">
                <div class="cursor-pointer" @click="retreatAppPage">
                    <ArrowLeftOutlined style="font-size: 16px;" :class="{ undo: ! canUndo }" />
                </div>
                <div class="ml-10 cursor-pointer" @click="forwardAppPage">
                    <ArrowRightOutlined style="font-size: 16px;" :class="{ undo: ! canRedo }"/>
                </div>
                <div class="ml-10 cursor-pointer">
                    <Loading3QuartersOutlined style="font-size: 16px;" @click="reloadAppPage"/>
                </div>
            </div>
            <div class="flex-1 overflow-hidden px-30">
                <div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                    {{ windowViewUrl }}
                </div>
            </div>
            
            <div class="flex align-center">
                <a-button size="small" style="border-radius: 4px;" @click="clearAppCache">清除缓存</a-button>
                <a-button type="link" @click="copyWindowUrl">复制链接</a-button>
            </div>
        </div>
        <div class="flex justify-center flex-1 align-center" ref="windowViewRef">
            <div><img src="../../../../common/image/loading.gif" style="transform:scale(.3)"/></div>
        </div>
    </div>
</template>

<style lang="less" scoped>
    .header {
        height: 35px;
        line-height: 35px;
        padding: 0 10px;
        background-color: #fff;
    }

    .undo {
        color: #ccc;
    }
</style>